package com.zlz.m3u8download.task;

import com.alibaba.fastjson2.JSON;
import com.zlz.m3u8download.bean.ResultSet;
import com.zlz.m3u8download.bean.RunTimeTask;
import com.zlz.m3u8download.controller.TaskWebSocket;
import com.zlz.m3u8download.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @Author: zhulinzhong
 * @Date: 2024/11/29
 */
@Component
@Slf4j
public class TaskJob {

    ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(
            5,
            5,
            60,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>()
    );

    @Resource
    private TaskService taskService;

    @Scheduled(fixedRate = 2000)
    public void task() {
        synchronized (CommonCache.class) {
            if (CommonCache.maxRunning()) {
                return;
            }
            // 优先调度高优先级队列
            if (!CommonCache.priorityTask.isEmpty()) {
                for (Long taskId : new ArrayList<>(CommonCache.priorityTask)) {
                    if (CommonCache.maxRunning()) {
                        return;
                    }
                    CommonCache.priorityTask.remove(taskId);
                    exec(taskId);
                }
            }

            // 调度普通队列
            if (CommonCache.maxRunning()) {
                return;
            }
            for (Long taskId : new ArrayList<>(CommonCache.waitingTasks)) {
                if (CommonCache.maxRunning()) {
                    return;
                }
                CommonCache.waitingTasks.remove(taskId);
                exec(taskId);
            }
        }
    }

    private void exec(Long task) {
        try {
            log.debug("本次任务调度任 TaskId:{}", task);
            RunTimeTask runTimeTask = RunTimeTask.builder().running(true).taskId(task).build();
            CommonCache.runningTasks.put(task, runTimeTask);
            threadPoolExecutor.execute(() -> {
                boolean execute = taskService.execute(runTimeTask);
                synchronized (CommonCache.class) {
                    if (execute) {
                        CommonCache.success(task);
                    } else {
                        CommonCache.waitTry(task);
                        log.debug("执行任务失败,已经加入高优先级队列,TaskId:{}", task);
                    }
                }
            });
        } catch (Exception e) {
            CommonCache.waitTry(task);
            log.debug("任务执行失败 TaskId:{}", task);
        }
    }

    @Scheduled(fixedRate = 1000)
    public void taskState() {
        TaskWebSocket.userTaskMap.forEach(TaskWebSocket::sendTaskMessage);
    }
}
